package com.example.hxds.dr.service.Impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.example.hxds.common.exception.HxdsException;
import com.example.hxds.common.util.MicroAppUtil;
import com.example.hxds.common.util.PageUtils;
import com.example.hxds.dr.db.dao.DriverDao;
import com.example.hxds.dr.db.dao.DriverSettingsDao;
import com.example.hxds.dr.db.dao.WalletDao;
import com.example.hxds.dr.db.pojo.DriverSettingsEntity;
import com.example.hxds.dr.db.pojo.WalletEntity;
import com.example.hxds.dr.service.DriverService;
import com.google.gson.JsonObject;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.iai.v20200303.IaiClient;
import com.tencentcloudapi.iai.v20200303.models.CreateFaceResponse;
import com.tencentcloudapi.iai.v20200303.models.CreatePersonRequest;
import com.tencentcloudapi.iai.v20200303.models.CreatePersonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author XUYANG
 * @Date 2024-03-09 9:31
 */
@Service
@Slf4j
public class DriverServiceImpl implements DriverService {
    @Value("${tencent.cloud.secretId}")
    private String secretId;
    @Value("${tencent.cloud.secretKey}")
    private String secretKey;
    @Value("${tencent.cloud.face.groupName}")
    private String groupName;
    @Value("${tencent.cloud.face.region}")
    private String region;
    @Resource
    private MicroAppUtil microAppUtil;
    @Resource
    private DriverDao driverDao;
    @Resource
    private DriverSettingsDao settingsDao;
    @Resource
    private WalletDao walletDao;
    @Override
    public String registerNewDriver(Map driver) {
        String code = MapUtil.getStr(driver,"code");
        //获取openId(用户唯一凭证)
        String openId=microAppUtil.getOpenId(code);
        HashMap tmpOpenId=new HashMap(){
            {
                put("openId",openId);
            }
        };
        if (driverDao.hasDriver(tmpOpenId)!=0){
            throw new HxdsException("该微信已经注册过");
        }
        driver.put("openId",openId);
        //插入注册记录
        driverDao.registerDriver(driver);
        //获取主键值
        String driverId=driverDao.searchDriverId(openId);
        //添加司机可设置记录
        DriverSettingsEntity settingsEntity=new DriverSettingsEntity();
        settingsEntity.setDriverId(Long.parseLong(driverId));
        JSONObject json=new JSONObject();
        json.set("orientation","");
        json.set("listenService",true);
        json.set("orderDistance",0);
        json.set("rangeDistance",5);
        json.set("autoAccept",false);
        settingsEntity.setSettings(json.toString());
        settingsDao.insertDriverSettings(settingsEntity);
        //添加司机钱包记录
        WalletEntity wallet=new WalletEntity();
        wallet.setDriverId(Long.parseLong(driverId));
        wallet.setBalance(new BigDecimal("0"));
        //支持支付密码为空，支付时会提示为空
        wallet.setPassword(null);
        walletDao.insert(wallet);
        return driverId;
    }

    @Override
    @Transactional
    @LcnTransaction
    public int updateDriverAuth(Map drAuth) {
        int rows=driverDao.updateDriverAuth(drAuth);
        return rows;
    }

    @Override
    @Transactional
    @LcnTransaction
    public String createDriverFaceModel(long driverId, String photo) {
        HashMap map=driverDao.searchDriverNameAndSex(driverId);
        String name=MapUtil.getStr(map,"name");
        String sex=MapUtil.getStr(map,"sex");
        Credential credential=new Credential(secretId,secretKey);
        IaiClient client=new IaiClient(credential,region);
        try {
            CreatePersonRequest request=new CreatePersonRequest();
            request.setGroupId(groupName);
            request.setPersonId(driverId+"");
            long gender=sex.equals("男")?1L:2L;
            request.setGender(gender);
            request.setQualityControl(4L);
            request.setUniquePersonControl(4L);
            request.setPersonName(name);
            request.setImage(photo);
            CreatePersonResponse response = client.CreatePerson(request);
            if (StrUtil.isNotBlank(response.getFaceId())){
                int rows = driverDao.updateDriverArchive(driverId);
                if (rows!=1){
                    return "更新司机归档失败";
                }
            }
        }catch (Exception e){
            log.error("创建腾讯云端司机档案失败",e);
            return "创建腾讯云端司机档案失败";
        }
        return "";
    }

    @Override
    public HashMap login(String code) {
        String openId=microAppUtil.getOpenId(code);
        HashMap res=driverDao.login(openId);
        if (res!=null&&res.containsKey("archive")){
            int tmp=MapUtil.getInt(res,"archive");
            boolean archive=(tmp==1)?true:false;
            res.replace("archive",archive);
        }
        return res;
    }

    @Override
    public HashMap searchDriverBaseInfo(long driverId) {
        HashMap result=driverDao.searchDriverBaseInfo(driverId);
        JSONObject summary= JSONUtil.parseObj(MapUtil.getStr(result,"summary"));
        result.replace("summary",summary);
        return result;
    }

    @Override
    public HashMap searchDriverSettings(long driverId) {
        String settings= settingsDao.searchDriverSettings(driverId);
        HashMap map=JSONUtil.parseObj(settings).toBean(HashMap.class);
        boolean isListenService=MapUtil.getInt(map,"listenService")==1?true:false;
        map.replace("listenService",isListenService);
        isListenService=MapUtil.getInt(map,"autoAccept")==1?true:false;
        map.replace("autoAccept",isListenService);
        return map;
    }

    @Override
    public PageUtils searchDriverByPage(Map param) {
        long count=driverDao.searchDriverCount(param);
        ArrayList list=null;
        if (count==0){
            list=new ArrayList();
        }else {
            list=driverDao.searchDriverByPage(param);
        }
        int start=(Integer) param.get("start");
        int length=(Integer) param.get("length");
        PageUtils pageUtils=new PageUtils(list,count,start,length);
        return pageUtils;
    }

    @Override
    public HashMap searchDriverAuth(long driverId) {
        HashMap res=driverDao.searchDriverAuth(driverId);
        return res;
    }

    @Override
    public HashMap searchDriverRealSummary(long driverId) {
        HashMap map=driverDao.searchDriverRealSummary(driverId);
        return map;
    }

    @Override
    @Transactional
    @LcnTransaction
    public int updateDriverRealAuth(Map param) {
        int rows=driverDao.updateDriverRealAuth(param);
        return rows;
    }

    @Override
    public HashMap searchDriverBriefInfo(long driverId) {
        HashMap res=driverDao.searchDriverBriefInfo(driverId);
        return res;
    }

    @Override
    public String searchDriverOpenId(long driverId) {
        String openId = driverDao.searchDriverOpenId(driverId);
        return openId;
    }
}
